import { ref, onMounted } from 'vue'
import type { Ref } from 'vue'
import type { IProduct } from '@/types/Types'
import { RequestCategoryList, RequestProductListByCategoryId } from '@/api/product'

interface ICategory {
	id: number
	text: string
}

interface IProductType {
	id: number
	name: string
}

/**
 * 分类业务
 */
export const useCategory = () => {
	const activeId = ref(1)
	const activeIndex = ref(0)
	let categoryList: Ref<Array<ICategory>> = ref([])
	let selectList: Ref<Array<IProduct>> = ref([])

	/**
	 * 商品分类列表
	 */
	const getCategoryList = async () => {
		let data = await RequestCategoryList()
		let { resultCode, resultInfo } = data
		if (resultCode == 1) {
			let list = resultInfo.list
			categoryList.value = list.map((item:IProductType) => {
				return { id: item.id, text: item.name }
			})

			getProductListByCategoryId(categoryList.value[0].id)
		}
	}

	/**
	 * 商品列表
	 */
	const getProductListByCategoryId = async (categoryId: number) => {
		let data = await RequestProductListByCategoryId(categoryId)
		let { resultCode, resultInfo } = data
		if (resultCode == 1) {
			selectList.value = resultInfo.list
		}
	}

	/**
	 * 选中分类
	 */
	const onSelector = (index: number) => {
		let categoryId = categoryList.value[index].id //商品分类id
		getProductListByCategoryId(categoryId)
	}

	onMounted(() => {
		getCategoryList()
	})

    return {
        activeId,
        activeIndex,
        categoryList,
        selectList,

        onSelector
    }
}
